package dantzig_wolfe_decomposition;

import Jama.Matrix;

public class dwDecomposition {
    public static void main(String[] args) {

        Solver solver = new Solver();
        solver.solve();

    }
}

class Solver {

    public final int plantNum;
    public final int[] plantVariableDimension;

    private boolean isOptimal = false;

    private Matrix[] extremePoints; // 系数矩阵，随着列生成的过程不断增加

    Solver() {
        this.plantNum = Dataset.benefit.length;
        this.plantVariableDimension = new int[plantNum];
        for (int i = 0; i < plantNum; i++) {
            plantVariableDimension[i] = Dataset.coal[i].length;
        }
        this.extremePoints = new Matrix[plantNum];
    }

    public void solve() {

        // 考虑到原点(0, 0)是案例中每一个变量组的极点，所以使用同一个函数获取初始极点
        for (int i = 0; i < plantNum; i++) {
            this.extremePoints[i] = getInitSolution(i);
        }

        // 根据初始的A求解主问题
        MainProblem mp = new MainProblem(this.extremePoints);
        mp.solve();

        while (!isOptimal) {
            int status = 0;
            for (int i = 0; i < plantNum; i++) {
                // 求解子问题
                SubProblem sp = new SubProblem(i, mp.shadowPrice);
                sp.solve();

                // 新增列
                if (sp.objVal < 0) {
                    int xNum = this.extremePoints[i].getColumnDimension();
                    Matrix temp = new Matrix(plantVariableDimension[i], xNum + 1, 0);
                    temp.setMatrix(0, plantVariableDimension[i] - 1, 0, xNum - 1, this.extremePoints[i]);
                    temp.setMatrix(0, plantVariableDimension[i] - 1, xNum, xNum, sp.solutions);
                    this.extremePoints[i] = temp.copy();
                } else {
                    status++;
                }
            }

            // 再求解主问题
            mp = new MainProblem(this.extremePoints);
            mp.solve();

            // 判断是否得到最优解
            if (status == 2) {
                isOptimal = true;
            }
        }

        // 输出最优解
        for (int i = 0; i < mp.solutions.length; i++) {
            System.out.println("");
            System.out.println("Plant " + (i + 1) + ":");

            Matrix temp = new Matrix(plantVariableDimension[i], 1, 0);
            for (int j = 0; j < mp.solutions[i].getRowDimension(); j++) {
                temp = temp.plus(this.extremePoints[i].getMatrix(0, plantVariableDimension[i] - 1, j, j)
                        .times(mp.solutions[i].get(j, 0)));
            }

            for (int j = 0; j < plantVariableDimension[i]; j++) {
                System.out.print("Steel " + (j + 1) + ": " + temp.get(j, 0));
                System.out.print("   ");
            }
        }

    }

    private Matrix getInitSolution(int i) {
        return new Matrix(plantVariableDimension[i], 1, 0);
    }

}
